package com.lemon.cloud.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lemon.cloud.admin.service.SysClientDetailsService;
import com.lemon.cloud.admin.dto.OAuthClientDTO;
import com.lemon.cloud.admin.entity.OAuthClientDetails;
import com.lemon.cloud.admin.mapper.ClientDetailsMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import static com.lemon.cloud.comm.constants.OAuth2Constant.ACCESS_TOKEN_VALIDITY_SECONDS;
import static com.lemon.cloud.comm.constants.OAuth2Constant.REFRESH_TOKEN_VALIDITY_SECONDS;

@Service
public class SysClientDetailsServiceImpl extends ServiceImpl<ClientDetailsMapper, OAuthClientDetails> implements SysClientDetailsService {

    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public OAuthClientDetails add(OAuthClientDTO dto) {
        OAuthClientDetails details = new OAuthClientDetails();
        BeanUtils.copyProperties(dto, details);
        if (dto.getAccessTokenValidity() == null) {
            details.setAccessTokenValidity((int) ACCESS_TOKEN_VALIDITY_SECONDS);
        }
        if (dto.getRefreshTokenValidity() == null) {
            details.setRefreshTokenValidity((int) REFRESH_TOKEN_VALIDITY_SECONDS);
        }
        details.setClientSecret(passwordEncoder.encode(dto.getClientSecret()));
        this.save(details);
        return details;
    }

    @Override
    public OAuthClientDetails updateDetails(OAuthClientDTO dto) {
        Assert.state(StringUtils.isNotEmpty(dto.getClientId()),"编码为空");

        OAuthClientDetails details = new OAuthClientDetails();
        BeanUtils.copyProperties(dto, details);
        if (dto.getAccessTokenValidity() == null) {
            details.setAccessTokenValidity((int) ACCESS_TOKEN_VALIDITY_SECONDS);
        }
        if (dto.getRefreshTokenValidity() == null) {
            details.setRefreshTokenValidity((int) REFRESH_TOKEN_VALIDITY_SECONDS);
        }
        details.setClientSecret(passwordEncoder.encode(dto.getClientSecret()));
        this.updateById(details);
        return details;
    }
}
